<template>
  <!-- 异常工单 -->
  <div v-if="!stationInfo?.id">
    <div
      class="workOrder"
      v-for="(item, index) in workBarList"
      :key="item"
      @click="selectWorkType(item, index)"
    >
      <div :class="['workBar', item.type, item.checked ? 'checked' : '']">
        <div class="workIcon"><CopyOutlined /></div>
        {{ item.name }}
        <div class="workNum">{{ item.num }}</div>
      </div>
    </div>
  </div>
  <div class="filterContent" v-if="!stationInfo?.id">
    <a-form :model="filterForm" layout="inline">
      <a-form-item label="工单编号">
        <a-input
          v-model:value="filterForm.serialCode"
          class="formInput"
          allow-clear
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="电站名称">
        <a-select
          v-model:value="filterForm.stationId"
          class="formInput"
          placeholder="请选择"
          allow-clear
          show-search
          optionFilterProp="label"
          :disabled="stationInfo?.id"
        >
          <a-select-option
            v-for="item in stationtList"
            :value="item.stationId"
            :key="item.stationId"
            :label="item.stationName"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="优先级">
        <a-select
          v-model:value="filterForm.exceptionPriority"
          class="formInput"
          placeholder="请选择"
          allow-clear
          show-search
          optionFilterProp="label"
        >
          <a-select-option
            v-for="item in WORK_ORDER_PRIORITY_LIST"
            :value="item.value"
            :key="item.value"
            :label="item.label"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="发起人">
        <a-input
          v-model:value="filterForm.createUserName"
          class="formInput"
          allow-clear
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="发起日期">
        <a-range-picker
          v-model:value="filterForm.createTime"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          picker="date"
          allowClear
          separator="~"
        />
      </a-form-item>
      <a-form-item label="处理人">
        <a-input
          v-model:value="filterForm.exceptionDealUserName"
          class="formInput"
          allow-clear
          placeholder="请输入"
        />
      </a-form-item>
      <a-button type="primary" class="filterBtn" @click="handleFilter"
        >查询</a-button
      >
      <a-button
        v-hasPermission="'errorOrderAdd'"
        type="primary"
        class="filterBtn greenBtn"
        @click="handleAdd"
        >新增</a-button
      >
    </a-form>
  </div>
  <div class="tableContent" ref="tableContainerRef">
    <a-table
      :dataSource="tableData"
      :columns="columns"
      size="small"
      :scroll="tableScroll"
      @resizeColumn="handleResizeColumn"
      :pagination="false"
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'workTicketNum'">
          {{ record?.workTicketDtoList?.length || "0" }}
        </template>
        <template v-if="column.key === 'priority'">
          <!-- 优先级 -->
          {{ WORK_ORDER_PRIORITY[record.priority] }}
        </template>
        <template v-if="column.key === 'handle'">
          <a-button
            v-hasPermission="'errorOrderTicket'"
            type="link"
            @click="handleTicket(record)"
            >工作票</a-button
          >
          <a-button
            v-hasPermission="'errorOrderInfo'"
            type="link"
            @click="handleDetail(record)"
            >详情</a-button
          >
          <a-button
            v-if="
              (selectType === WORK_ORDER_STATUS_ENUM.SUM ||
                selectType === WORK_ORDER_STATUS_ENUM.AUDIT) &&
              record.state === WORK_ORDER_STATUS_ENUM.AUDIT
            "
            v-hasPermission="'errorOrderAudit'"
            type="link"
            @click="handleAudit(record)"
            >审核</a-button
          >
          <a-button
            v-if="
              (selectType === WORK_ORDER_STATUS_ENUM.SUM ||
                selectType === WORK_ORDER_STATUS_ENUM.CLAIM) &&
              record.state === WORK_ORDER_STATUS_ENUM.CLAIM
            "
            type="link"
            @click="handleClaim(record)"
            v-hasPermission="'errorOrderClaim'"
            >认领</a-button
          >
          <a-button
            v-if="
              (selectType === WORK_ORDER_STATUS_ENUM.SUM ||
                selectType === WORK_ORDER_STATUS_ENUM.HANDLE) &&
              record.state === WORK_ORDER_STATUS_ENUM.HANDLE
            "
            type="link"
            @click="handleError(record)"
            v-hasPermission="'errorOrderError'"
            >处理</a-button
          >
          <a-button
            v-if="
              (selectType === WORK_ORDER_STATUS_ENUM.SUM ||
                selectType === WORK_ORDER_STATUS_ENUM.COMFIRM) &&
              record.state === WORK_ORDER_STATUS_ENUM.COMFIRM
            "
            type="link"
            @click="handleComfirm(record)"
            v-hasPermission="'errorOrderConfirm'"
            >确认</a-button
          >
        </template>
      </template>
    </a-table>
    <a-pagination
      v-model:current="filterForm.current"
      v-model:page-size="filterForm.size"
      :total="total"
      position="bottomRight"
      show-size-changer
      @change="getOrderList"
      :show-total="(total) => `总共 ${total} 条`"
    >
      <template #buildOptionText="props">
        <span>{{ props.value }}条/页</span>
      </template>
    </a-pagination>
  </div>
  <!-- 新增工单 -->
  <AddErrorOrder
    :addOrderVisible="addOrderVisible"
    :rowData="rowData"
    :stationtList="stationtList"
    :workOrderType="WORK_ORDER_TYPE.ERROR"
    @update:addOrderVisible="(val) => (addOrderVisible = val)"
    @getOrderList="getOrderList"
  />
  <!-- 详情 -->
  <DetailsInfo
    :detailVisible="detailVisible"
    :rowData="rowData"
    :workOrderType="WORK_ORDER_TYPE.ERROR"
    @update:detailVisible="(val) => (detailVisible = val)"
    @getOrderList="getOrderList"
  />
  <!-- 认领工单 -->
  <ClaimOrder
    :claimOrderVisible="claimOrderVisible"
    :rowData="rowData"
    :workOrderType="WORK_ORDER_TYPE.ERROR"
    @update:claimOrderVisible="(val) => (claimOrderVisible = val)"
    @getOrderList="getOrderList"
  />
  <!-- 处理工单 -->
  <HandleErr
    :handleErrVisible="handleErrVisible"
    :rowData="rowData"
    :workOrderType="WORK_ORDER_TYPE.ERROR"
    @update:handleErrVisible="(val) => (handleErrVisible = val)"
    @getOrderList="getOrderList"
  />
  <!-- 确认工单 -->
  <ConfirmOrder
    :confirmOrderVisible="confirmOrderVisible"
    :rowData="rowData"
    :workOrderType="WORK_ORDER_TYPE.ERROR"
    @update:confirmOrderVisible="(val) => (confirmOrderVisible = val)"
    @getOrderList="getOrderList"
  />
  <!-- 工单审核 -->
  <ErrorOrderAudit
    :errorOrderAuditVisible="errorOrderAuditVisible"
    :rowData="rowData"
    @update:errorOrderAuditVisible="(val) => (errorOrderAuditVisible = val)"
    @getOrderList="getOrderList"
  />
  <!-- 工作票详情 -->
  <TicketInfo
    :ticketInfoVisible="ticketInfoVisible"
    :rowData="rowData"
    :stationtList="stationtList"
    @update:ticketInfoVisible="(val) => (ticketInfoVisible = val)"
  />
</template>
<script setup>
// 
import AddErrorOrder from "./conpoments/addErrOrder.vue"
import useTableScroll from "@/hooks/useTableScroll"
import DetailsInfo from "./conpoments/errorDetailsInfo.vue"
import ClaimOrder from "./conpoments/claimErrorOrder.vue"
import HandleErr from "./conpoments/handleErr.vue"
import ConfirmOrder from "./conpoments/confirmOrder.vue"
import ErrorOrderAudit from "./conpoments/errorOrderAudit.vue"
import TicketInfo from "./conpoments/ticketInfo.vue"

import {
  WORK_ORDER_TYPE,
  WORK_ORDER_PRIORITY_LIST,
  WORK_ORDER_PRIORITY,
  WORK_ORDER_STATUS_ENUM,
} from "@/constants/workOrder"

const route = useRoute()
const props = defineProps({
  stationInfo: {
    type: Object,
  },
})
const $api = inject("$api")
const filterForm = ref({
  serialCode: undefined,
  stationId: undefined,
  exceptionPriority: undefined,
  exceptionDealUserName: undefined,
  size: 10,
  current: 1,
  createTime: undefined,
  createUserName: undefined,
})
const total = ref()
const detailVisible = ref(false)
const addOrderVisible = ref(false)
const claimOrderVisible = ref(false)
const handleErrVisible = ref(false)
const confirmOrderVisible = ref(false)
const errorOrderAuditVisible = ref(false)
const ticketInfoVisible = ref(false)
const tableData = ref([])
const rowData = ref({})
const tableLoading = ref(false)
const workBarList = ref([
  {
    name: "工单总数",
    type: "SUM",
    num: 0,
    value: "sum",
    filter: "",
    checked: true,
  },
  {
    name: "待审核工单",
    type: "AUDIT",
    num: 0,
    filter: WORK_ORDER_STATUS_ENUM.AUDIT,
    value: "approve",
    checked: false,
  },
  {
    name: "待认领工单",
    type: "CLAIM",
    num: 0,
    filter: WORK_ORDER_STATUS_ENUM.CLAIM,
    value: "claim",
    checked: false,
  },
  {
    name: "待处理工单",
    type: "HANDLE",
    filter: WORK_ORDER_STATUS_ENUM.HANDLE,
    value: "deal",
    num: 0,
    checked: false,
  },
  {
    name: "待确认工单",
    type: "COMFIRM",
    num: 0,
    filter: WORK_ORDER_STATUS_ENUM.COMFIRM,
    value: "confirm",
    checked: false,
  },
  {
    name: "已完结工单",
    type: "FINISH",
    num: 0,
    filter: WORK_ORDER_STATUS_ENUM.FINISH,
    value: "finish",
    checked: false,
  },
  {
    name: "已驳回工单",
    type: "RETURN",
    num: 0,
    filter: WORK_ORDER_STATUS_ENUM.REJECT,
    value: "reject",
    checked: false,
  },
])
const columns = ref([
  {
    title: "工单编号",
    dataIndex: "serialCode",
    key: "serialCode",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    width: 200,
    resizable: true,
    align: "center",
  },
  {
    title: "工单状态",
    dataIndex: "stateStr",
    key: "stateStr",
    width: 130,
    resizable: true,
    align: "center",
  },
  {
    title: "问题描述",
    dataIndex: "exceptionDesc",
    key: "exceptionDesc",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "运营部建议",
    dataIndex: "exceptionOperateSuggest",
    key: "exceptionOperateSuggest",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "工单审核意见",
    dataIndex: "exceptionApproveOperation",
    key: "exceptionApproveOperation",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "优先级",
    dataIndex: "exceptionPriorityStr",
    key: "exceptionPriorityStr",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "关联工作票个数",
    dataIndex: "workTicketNum",
    key: "workTicketNum",
    width: 80,
    resizable: true,
    align: "center",
  },
  {
    title: "工单处理人",
    dataIndex: "exceptionDealUserName",
    key: "exceptionDealUserName",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "工单处理描述及措施",
    dataIndex: "exceptionDealDesc",
    key: "exceptionDealDesc",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "工单处理时间",
    dataIndex: "exceptionDealDate",
    key: "exceptionDealDate",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "工单发起人",
    dataIndex: "createUserName",
    key: "createUserName",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "工程部处理时长(h)",
    dataIndex: "exceptionDealTime",
    key: "exceptionDealTime",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    //width: 120,
    align: "center",
    fixed: "right",
  },
])
function handleResizeColumn(w, col) {
  col.width = w
}
const handleAdd = () => {
  addOrderVisible.value = true
}
const handleClaim = (data) => {
  rowData.value = data
  claimOrderVisible.value = true
}
const handleError = (data) => {
  rowData.value = data
  handleErrVisible.value = true
}
const handleComfirm = (data) => {
  rowData.value = data
  confirmOrderVisible.value = true
}

const handleEdit = async (data) => {
  rowData.value = data
}
const tableContainerRef = ref(null)
const handleFilter = () => {
  filterForm.value.current = 1
  filterForm.value.size = 10
  getOrderList()
}
const stationtList = ref([])
const getCompanyStationtList = async () => {
  const res = await $api.companyStationtList()
  if (res?.code === 0) {
    stationtList.value = res.data
  }
}

const selectType = ref(WORK_ORDER_STATUS_ENUM.SUM)
const selectWorkType = (item, index) => {
  selectType.value = item.filter
  for (const item of workBarList.value) {
    item.checked = false
  }
  workBarList.value[index].checked = true
  getOrderList(true)
}
const handleDetail = (data) => {
  rowData.value = data
  detailVisible.value = true
}
const handleTicket = (data) => {
  rowData.value = data
  ticketInfoVisible.value = true
}
const handleAudit = (data) => {
  rowData.value = data
  errorOrderAuditVisible.value = true
}
const getOrderList = async (isFilter = false) => {
  const { createTime, ...rest } = filterForm.value
  const params = {
    ...rest,
    type: WORK_ORDER_TYPE.ERROR,
    inspectionDate: filterForm.value.inspectionDate?.join(","),
  }
  if (filterForm.value.createTime?.length) {
    params.startTime = filterForm.value.createTime?.[0] + " 00:00:00"
    params.endTime = filterForm.value.createTime?.[1] + " 23:59:59"
  }
  if (selectType.value !== WORK_ORDER_TYPE.SUM) {
    params.state = workBarList.value.find((item) => item.checked).filter
  }
  tableLoading.value = true
  if (!isFilter && !props.stationInfo?.id) {
    // 通过顶部工单状态点击筛选，和单站管理进来的工单，不需要请求工单数量接口
    getWorkOrderCount(params)
  }
  const res = await $api.workOrderList(params)
  tableLoading.value = false
  if (res && res.code === 0) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
const getWorkOrderCount = async (params) => {
  params.state = ""
  const res = await $api.workOrderCount(params)
  if (res && res.code === 0) {
    for (const item of workBarList.value) {
      item.num = res.data[item.value] || "0"
    }
  }
}
const setStation = () => {
  // 如果有 stationInfo 数组，则是从单站管理-故障监控-未完成工单页面进来的，需要设置电站进行列表过滤
  if (props.stationInfo?.id) {
    filterForm.value.stationId = props.stationInfo.id
    filterForm.value.stateList = [
      WORK_ORDER_STATUS_ENUM.AUDIT,
      WORK_ORDER_STATUS_ENUM.CLAIM,
      WORK_ORDER_STATUS_ENUM.HANDLE,
      WORK_ORDER_STATUS_ENUM.COMFIRM,
    ]
  }
}
onMounted(async () => {
  if (
    Object.keys(route.query).length > 0 &&
    route.query?.workOrderCode !== null
  ) {
    filterForm.value.serialCode = route.query.workOrderCode
  }
  setStation()
  getOrderList()
  getCompanyStationtList()
})

const handleChageStation = () => {
  setStation()
  getOrderList()
}
const { tableScroll } = useTableScroll(tableData, tableContainerRef, 110)
defineExpose({ handleChageStation })
</script>

<style lang="less" scoped>
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.formInput {
  width: 155px;
}
.filterBtn {
  margin: 0 20px 20px 0;
  &:last-child {
    margin-right: 0;
  }
}
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
.workOrder {
  margin: 10px 20px 20px 0;
  display: inline-block;
  cursor: pointer;
  .workBar {
    width: 180px;
    height: 55px;
    line-height: 55px;
    position: relative;
    border-radius: 4px;
  }
  .workIcon {
    width: 28px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    display: inline-block;
    border-radius: 50%;
    margin: 0 15px 0 10px;
  }
  .workNum {
    margin-left: 20px;
    position: absolute;
    right: 8px;
    top: 0px;
  }
  .SUM {
    border: 1px solid #1990ff;
    .workNum {
      color: rgba(25, 144, 255);
    }
    .workIcon {
      background: rgba(25, 144, 255);
    }
    .checked {
      background: rgba(25, 144, 255, 0.3);
    }
    &[class*=" checked"] {
      background: rgba(25, 144, 255, 0.3);
    }
  }
  .CLAIM {
    border: 1px solid #30c25b;
    .workNum {
      color: #30c25b;
    }
    .workIcon {
      background: #30c25b;
    }
    &[class*=" checked"] {
      background: rgba(48, 194, 91, 0.3);
    }
  }
  .HANDLE {
    border: 1px solid rgb(250 204 20);
    .workNum {
      color: rgb(250 204 20);
    }
    .workIcon {
      background: rgb(250 204 20);
    }
    &[class*=" checked"] {
      background: rgba(250, 204, 20, 0.3);
    }
  }
  .COMFIRM {
    border: 1px solid rgb(22 194 195);
    .workNum {
      color: rgb(22 194 195);
    }
    .workIcon {
      background: rgb(22 194 195);
    }
    &[class*=" checked"] {
      background: rgba(22, 194, 195, 0.3);
    }
  }
  .FINISH {
    border: 1px solid rgba(240, 72, 100, 1);
    .workNum {
      color: rgba(240, 72, 100, 1);
    }
    .workIcon {
      background: rgba(240, 72, 100, 1);
    }
    &[class*=" checked"] {
      background: rgba(240, 72, 100, 0.3);
    }
  }
  .AUDIT {
    border: 1px solid #f59a23;
    .workNum {
      color: #f59a23;
    }
    .workIcon {
      background: #f59a23;
    }
    &[class*=" checked"] {
      background: rgba(245, 154, 35, 0.3);
    }
  }
  .RETURN {
    border: 1px solid rgb(215 215 215);
    .workNum {
      color: rgb(215 215 215);
    }
    .workIcon {
      background: rgb(215 215 215);
    }
    &[class*=" checked"] {
      background: rgba(215, 215, 215, 0.3);
    }
  }
}
</style>
